import hashlib
import mimetypes
import os
import time
import uuid
from hashlib import md5

from django.conf import settings
from django.core.files.base import ContentFile
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from hot import models
from hot.forms.index import ContentForm


def home(request):
    return render(request, 'index/index.html')


def welcome(request):
    return render(request, 'index/welcome.html')


def list(request, priority_id=None):
    title_lst = ['ID', '小标题', '内容', '图片', '栏目', '状态', '操作']
    if request.method == 'GET':
        if priority_id is None:
            content_list = models.ContentManage.objects.filter(content_category__category_name='首页',
                                                               ).order_by(
                'content_priority')
        else:
            content_list = models.ContentManage.objects.filter(content_category__category_name='首页',
                                                               content_priority=priority_id).order_by(
                'content_priority')
        category = models.Category.objects.filter(category_name='首页').first()

        return render(request, 'manage/list.html',
                      {'contents': content_list, 'nums': range(1, category.priority_num + 1)
                          , 'title_lst': title_lst},
                      )


def add(request):
    """增加"""
    if request.method == 'GET':
        category = models.Category.objects.filter(category_name='首页').first()

        return render(request, 'manage/add.html', {'nums': range(1, category.priority_num + 1)})
    form = ContentForm(data=request.POST)
    print(request.POST)
    if not form.is_valid():
        return JsonResponse({'code': '-1', 'data': form.errors})

    files = request.FILES.getlist('files')

    # 创建一个新的 ContentManage 实例，并设置其他字段的值
    try:
        new_content_instance = models.ContentManage.objects.create(**form.cleaned_data, content_category_id=1)

        # 传入文件对象
        for file in files:
            type = file.name.split('.')[-1]
            file.name = hashlib.md5(str(time.time()).encode()).hexdigest() + str(uuid.uuid4()) + '.' + type
            if file.content_type.startswith('image'):
                img_instance = models.ImgModel.objects.create(
                    content_img=ContentFile(file.read(), file.name),
                )
                # 对于视频文件，您可能希望直接使用FileField
            elif file.content_type.startswith('video'):
                img_instance = models.ImgModel.objects.create(
                    content_img=file,
                )
            new_content_instance.content_imgs.add(img_instance)

        return JsonResponse({'code': '200', 'data': '/index/list/'})
    except Exception as e:
        print(e)
        return JsonResponse({'code': '200', 'data': '/index/list/'})


def sub_file(request):
    """上传文件"""
    print(request.POST)
    print(request.FILES)
    return JsonResponse({'status': '200', 'data': 'ok'})


def delete(request):
    """删除"""
    index_id = int(request.POST.get('index_id'))
    obj = models.ContentManage.objects.filter(content_id=index_id).first()

    for img_instance in obj.content_imgs.all():
        try:
            img_path = os.path.join(settings.MEDIA_ROOT, img_instance.content_img.name)
            os.remove(img_path)
            print(f"Image file {img_path} deleted successfully.")
        except FileNotFoundError:
            print(f"Image file {img_path} not found.")
        except Exception as e:
            print(f"Error deleting image file {img_path}: {e}")

    obj.delete()

    return JsonResponse({'status': '200', 'data': 'ok'})


def active(request):
    """启用"""
    index_id = int(request.POST.get('index_id'))
    active = int(request.POST.get('active'))
    models.ContentManage.objects.filter(content_id=index_id).update(active=active)
    return JsonResponse({'status': '200', 'data': 'ok'})


from django.core.files.base import ContentFile


def edit(request, id):
    if request.method == 'GET':
        category = models.Category.objects.filter(category_name='首页').first()
        form = models.ContentManage.objects.filter(content_id=id).first()
        print(form.content_imgs.count())
        return render(request, 'manage/edit.html', {'nums': range(1, category.priority_num + 1), 'form': form})

    form = ContentForm(data=request.POST)
    if not form.is_valid():
        return JsonResponse({'code': '-1', 'data': form.errors})

    files = request.FILES.getlist('files')
    print(request.POST)
    print(request.FILES)

    try:
        content_instance = models.ContentManage.objects.filter(content_id=id)

        # 删除文件:
        for img_instance in content_instance.first().content_imgs.all():
            try:
                img_path = os.path.join(settings.MEDIA_ROOT, img_instance.content_img.name)
                os.remove(img_path)
            except Exception as e:
                print(f"Error deleting image file {img_path}: {e}")

        content_instance.first().content_imgs.all().delete()

        content_instance.update(**form.cleaned_data, content_category_id=1)

        # 为新的实例添加新的图片文件
        for file in files:
            type = file.name.split('.')[-1]
            file.name = hashlib.md5(str(time.time()).encode()).hexdigest() + str(uuid.uuid4()) + '.' + type
            img_instance = models.ImgModel.objects.create(
                content_img=ContentFile(file.read(), file.name),
            )
            content_instance.first().content_imgs.add(img_instance)

        return JsonResponse({'code': '200', 'data': '/index/list/'})
    except Exception as e:
        print(e)
    return JsonResponse({'code': '500', 'data': '/index/list/'})


def delete_all(request):
    """删除全部"""
    lst = request.POST.getlist('selected_ids[]')
    for i in lst:
        obj = models.ContentManage.objects.filter(content_id=i).first()
        for img_instance in obj.content_imgs.all():
            try:
                img_path = os.path.join(settings.MEDIA_ROOT, img_instance.content_img.name)
                os.remove(img_path)
                print(f"Image file {img_path} deleted successfully.")
            except FileNotFoundError:
                print(f"Image file {img_path} not found.")
            except Exception as e:
                print(f"Error deleting image file {img_path}: {e}")

        obj.delete()

    return JsonResponse({'status': '200', 'data': 'ok'})
